package com.hang.ad.index.creative;

import com.hang.ad.index.IndexAware;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class CreativeIndex implements IndexAware<Long, CreativeObject> {
    private static Map<Long, CreativeObject> map;
    static {
        map = new ConcurrentHashMap<>();
    }
    public List<CreativeObject> fetch(Collection<Long> adIds){
        if (CollectionUtils.isEmpty(adIds)){
            return Collections.emptyList();
        }
        List<CreativeObject> result = new ArrayList<>();

        adIds.forEach(u -> {
            CreativeObject creativeObject = get(u);
            if (creativeObject == null){
                log.error("creativeObject not found");
                return;
            }

            result.add(creativeObject);
        });
        return result;
    }

    @Override
    public CreativeObject get(Long key) {
        return map.get(key);
    }

    @Override
    public void update(Long key, CreativeObject value) {
        CreativeObject creativeObject = map.get(key);
        if (creativeObject == null){
            map.put(key, value);
        }else {
            creativeObject.update(value);
        }
    }

    @Override
    public void add(Long key, CreativeObject value) {
        map.put(key, value);
    }

    @Override
    public void delete(Long key, CreativeObject value) {
        map.remove(key);
    }
}
